const express = require("express")
const mongoose = require("mongoose")
const bodyParser = require("body-parser")
const passprot = require("passport")

const port = process.env.PORT || 5000
const app = new express()
mongoose.set("useFindAndModify", false)
// 使用body-parser插件来处理post请求的数据
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


// Router 
// 引入user.js
const users = require("./routers/api/users")
// 引入profiles.js
const profiles = require("./routers/api/profiles")

// DB config
const db = require("./config/keys").mongoURI

// connect to Mongodb
// mongoose.connect(db) 这种连接方式会报警告，DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, 
// pass option { useNewUrlParser: true } to MongoClient.connect.
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {
  console.log("Mongodb connected!")
}).catch(err => {
  console.log(err)
})

// 使用passport
app.use(passprot.initialize())
// token校验的代码放在passport.js文件里面
require("./config/passprot")(passprot)

// 使用routers
app.use("/api/users", users)
app.use("/api/profiles", profiles)

app.listen(port, () => {
  console.log(`Server running on ${port}`)
})